package tk.uodrad.apex.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tk.uodrad.apex.project.mapper.CommunityMapper;
import tk.uodrad.apex.project.pojo.dto.CommunityAddNewDTO;
import tk.uodrad.apex.project.pojo.dto.CommunityUpdateDTO;
import tk.uodrad.apex.project.pojo.entity.Community;
import tk.uodrad.apex.project.service.CommunityService;
import tk.uodrad.apex.project.web.JsonResult;

import java.util.Arrays;

/**
 * 说明：
 */
@Slf4j
@RestController
@RequestMapping("/community")
@Transactional
public class CommunityController {
    @Autowired
    private CommunityService communityService;
    @Autowired
    private CommunityMapper communityMapper;
    /**
     * 添加小区
     * @param communityAddNewDTO 添加小区DTO
     * */
    @PostMapping("/add")
    public JsonResult<String> add(@RequestBody CommunityAddNewDTO communityAddNewDTO) {
        communityService.save(communityAddNewDTO);
        return JsonResult.ok("添加成功");
    }

    /**
     * 根据ID数组删除小区
     * @param ids ID数组
     * */
    @GetMapping("/delete")
    public JsonResult<String> deleteById(Long[] ids) {
        communityService.removeByIds(Arrays.asList(ids));
        return JsonResult.ok("删除成功！");
    }

    /**
     * 根据ID删除小区
     * @param id 小区ID
     * */
    @PostMapping("/{id:[0-9]+}/delete")
    public JsonResult<Void> delete(@PathVariable @Range(min = 1, message = "请提交有效的ID值！") Long id){
        communityService.removeById(id);
        return JsonResult.ok();
    }

    /**
     * 根据ID修改小区信息
     * @param communityUpdateDTO 修改小区DTO
     * */
    @PostMapping("/update")
    public JsonResult<String> update(@RequestBody CommunityUpdateDTO communityUpdateDTO) {
        communityService.updateById(communityUpdateDTO);
        return JsonResult.ok("修改成功！");
    }

    /**
     * 分页查询小区列表
     * @param pageNum 第几页
     * @param pageSize 每页多少条数据
     * @return IPage<Community> 分页对象
     * */
    @GetMapping("/list")
    public JsonResult<IPage<Community>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "1000000000") Integer pageSize) {
        IPage<Community> list = communityService.list(pageNum, pageSize);
        return JsonResult.ok(list);
    }

    /**
     * 根据小区id查询详情
     * */
    @GetMapping("/{id:[0-9]+}")
    public JsonResult<Community> getListById(
            @PathVariable @Range(min = 1, message = "请提交有效的ID值！") Long id){
        Community queryResult = communityMapper.selectById(id);
        return JsonResult.ok(queryResult);
    }
}
